package com.situ.crm.controller;

import com.situ.crm.dao.IUserDao;
import com.situ.crm.dao.impl.UserDaoImpl;
import com.situ.crm.pojo.User;
import com.situ.crm.util.JSONUtil;
import com.situ.crm.util.Result;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private IUserDao userDao = new UserDaoImpl();

    // http://localhost:8088/user?method=selectAll
    // http://localhost:8088/user?method=deleteById&id=12
    //访问Servlet默认访问service方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决post请求中文乱码问题
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        if (StringUtils.isEmpty(method)) {
            method = "selectAll";
        }
        switch (method) {
            case "selectAll":
                selectAll(req, resp);
                break;
            case "deleteById":
                deleteById(req, resp);
                break;
            case "deleteAll":
                deleteAll(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "toUpdate":
                toUpdate(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
        }
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idsStr = req.getParameter("ids");// "12,23"
        String[]  ids = idsStr.split(",");// ["12", "23"]
        for (String id : ids) {
            userDao.deleteById(Integer.parseInt(id));
        }
        resp.sendRedirect("/user?method=selectAll");
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect("/login.jsp");
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        String code = req.getParameter("code");
        //先判断验证码对不对
        //验证码不正确，直接返回错误提示
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            JSONUtil.toJSON(resp, Result.error("验证码错误"));
            return;
        }

        //验证码正确，再判断用户名密码对不对
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        User user = userDao.login(name, password);
        if (user == null) {
            //用户名密码错误
            JSONUtil.toJSON(resp, Result.error("用户名密码错误"));
        } else {
            if (user.getStatus() == 0) {
                JSONUtil.toJSON(resp, Result.error("该用户被禁用"));
                return;
            }

            //登录成功,将登录成功的凭证放到session
            session.setAttribute("user", user);
            JSONUtil.toJSON(resp, Result.ok("登录成功"));
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String role = req.getParameter("role");// "1" => 1
        String image = req.getParameter("image");
        String status = req.getParameter("status");
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setName(name);
        user.setPassword(password);
        user.setRole(Integer.parseInt(role));
        user.setImage(image);
        user.setEmail(email);
        user.setStatus(Integer.parseInt(status));

        userDao.update(user);
        //修改完成之后应该查找对象的数据
        resp.sendRedirect("/user?method=selectAll");
    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User user = userDao.selectById(Integer.parseInt(id));

        req.setAttribute("user", user);
        req.getRequestDispatcher("user_update.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String role = req.getParameter("role");// "1" => 1
        String image = req.getParameter("image");
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setRole(Integer.parseInt(role));
        user.setImage(image);
        user.setEmail(email);

        userDao.add(user);

        //添加完成之后应该查找对象的数据
        resp.sendRedirect("/user?method=selectAll");
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        userDao.deleteById(Integer.parseInt(id));

        //删除完成之后应该查找对象的数据
        resp.sendRedirect("/user?method=selectAll");
    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        if (StringUtils.isEmpty(name)) {
            name = "";
        }
        List<User> list = userDao.selectAll(name);

        //把数据放到req这个域对象（可以理解成一块内存区域）
        req.setAttribute("list", list);
        //转发到user_list.jsp页面进行展示
        req.getRequestDispatcher("user_list.jsp").forward(req, resp);
    }
}
